package com.sec.etech.bpm.groovy;

import com.sec.etech.bpm.constant.DBConstant;
import com.sec.etech.org.service.EtechGroupService;
import com.sec.etech.org.service.EtechUserService;
import com.sec.etech.org.service.EtechUserUtil;
import com.sec.etech.sys.util.ContextUtil;
import org.openbpm.base.core.util.AppUtil;
import org.openbpm.base.core.util.StringUtil;
import org.openbpm.org.api.model.IUser;
import org.openbpm.org.api.service.UserService;
import org.openbpm.sys.api.groovy.IScript;
import org.openbpm.sys.api.model.DefaultIdentity;
import org.openbpm.sys.api.model.SysIdentity;
import org.openbpm.sys.api.service.ISysDataSourceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 定制常用脚本
 * <p>
 * 系统已提供SysScript, OrgScript, BpmScriptUtil, BusDataScript
 */
@Component
public class EtechBpmScript implements IScript {
    protected Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    UserService userService;
    @Resource
    EtechUserService etechUserService;
    @Autowired
    ISysDataSourceService sysDataSourceService;
    @Autowired
    EtechGroupService etechGroupService;

    public Object getBean(String beanName) {
        return AppUtil.getBean(beanName);
    }

    public Set<SysIdentity> constructeIdentityUser(String id) {
        if (StringUtil.isEmpty(id)) {
            return Collections.emptySet();
        }
        IUser user = this.userService.getUserById(id);
        if (!StringUtil.isEmpty(id) && user != null && !StringUtil.isEmpty(user.getFullname())) {
            Set<SysIdentity> identities = new LinkedHashSet(1);
            SysIdentity identity = new DefaultIdentity(id, user.getFullname(), "user");
            identities.add(identity);
            return identities;
        } else {
            this.log.warn("表单取候选人失败，表单字段为空 ： constructeIdentityUser id:{}", id);
            return Collections.emptySet();
        }
    }

    //保证脚本传来的用户id是BigDecimal格式时也能解析出正确的用户
    public Set<SysIdentity> constructeIdentityUser(BigDecimal id) {
        long a = id.longValue();
        return constructeIdentityUser(Long.toString(a));
    }

    //保证脚本传来的用户id是Long格式时也能解析出正确的用户
    public Set<SysIdentity> constructeIdentityUser(Long id) {
        return constructeIdentityUser(id.toString());
    }

    public Set<SysIdentity> constructeIdentityUsers(List<String> ids) {
        Set<SysIdentity> identities = new LinkedHashSet<>();
        if (ids != null && !CollectionUtils.isEmpty(ids)) {
            for (String id : ids) {
                IUser user = this.userService.getUserById(id);
                if (user != null && !StringUtil.isEmpty(user.getFullname())) {
                    SysIdentity identity = new DefaultIdentity(id, user.getFullname(), "user");
                    identities.add(identity);
                }
            }
        } else {
            this.log.warn("表单取候选人失败，表单字段为空 ： constructeIdentityUser id:{}", ids);
            return Collections.emptySet();
        }
        return identities;
    }

    //当用户id是一个用英文逗号拼接的字符串时，使用此方法，如：“740,1128,10229977”，返回三个人的Set
    public Set<SysIdentity> constructeIdentityUsersFromSpliceUserid(String ids) {
        Set<SysIdentity> identities = new LinkedHashSet<>();
        if (ids != null) {
            String[] idList = ids.split(",");
            for (String id : idList) {
                IUser user = this.userService.getUserById(id);
                if (user != null && !StringUtil.isEmpty(user.getFullname())) {
                    SysIdentity identity = new DefaultIdentity(id, user.getFullname(), "user");
                    identities.add(identity);
                }
            }
        } else {
            this.log.warn("表单取候选人失败，表单字段为空 ： constructeIdentityUser id:{}", ids);
            return Collections.emptySet();
        }
        return identities;
    }

    /**
     * 获取FX科室的计划班组长
     *
     * @param deptId
     * @param fType
     * @return
     */
    public Set<SysIdentity> getHandlersByDeptId(Long deptId, String fType) {
        JdbcTemplate jdbcTemplate = sysDataSourceService.getJdbcTemplateByKey(DBConstant.PLAN_DB);
        String sql = null;
        if ("F2".equalsIgnoreCase(fType)) {
            sql = "select uid from proj_plantask_z_designdprt_managers where active = 1 and designdprtid=" +
                    "(select designdprtid from proj_plantask_z_designdprt where dprtid = (select F2dprtid from proj_plantask_z_designdprt where designdprtid=" + deptId + "))";
        }
        if ("F3".equalsIgnoreCase(fType)) {
            sql = "select uid from proj_plantask_z_designdprt_managers where active = 1 and designdprtid=" +
                    "(select designdprtid from proj_plantask_z_designdprt where dprtid = (select F3dprtid from proj_plantask_z_designdprt where designdprtid=" + deptId + "))";
        }
        List<String> userIds = jdbcTemplate.queryForList(sql, String.class);//查询F节点科室计划班组长
        return this.constructeIdentityUsers(userIds);
    }

    /**
     * 根据设计科室获取计划负责人/计划员
     *
     * @param deptId
     * @return
     */
    public Set<SysIdentity> getHandlersByDeptId(Long deptId) {
        JdbcTemplate jdbcTemplate = sysDataSourceService.getJdbcTemplateByKey(DBConstant.PLAN_DB);
        String sql = "select uid from proj_plantask_z_designdprt_planners where active = 1 and designdprtid=" + deptId;
        List<String> userIds = jdbcTemplate.queryForList(sql, String.class);
        return this.constructeIdentityUsers(userIds);
    }

    /**
     * “产品图纸”、“外购件“和“英文图纸“的流程T1节点处理人
     */
    public Set<SysIdentity> getT1Handler(Long deptId, Long plantaskid) {
        Set<SysIdentity> handlers = getHandlersByDeptId(deptId);
        JdbcTemplate jdbcTemplate = sysDataSourceService.getJdbcTemplateByKey(DBConstant.PLAN_DB);
        String sql = "SELECT approveruid FROM proj_plantask_designer WHERE plantaskid = ?";
        List<String> approverList = jdbcTemplate.queryForList(sql, String.class, plantaskid);
        approverList = approverList.stream().filter(StringUtil::isNotEmpty).collect(Collectors.toList());
        if (approverList.size() > 0) {
            handlers.addAll(constructeIdentityUsers(approverList));
        }
        return handlers;
    }

    /**
     * 根据部门科室获取计划负责人/计划员
     *
     * @param deptId
     * @return
     */
    public Set<SysIdentity> getHandlersByDeptIdOther(Long deptId) {
        JdbcTemplate jdbcTemplate = sysDataSourceService.getJdbcTemplateByKey(DBConstant.PLAN_DB);
        String sql = "select p.uid from proj_plantask_z_designdprt_planners p,proj_plantask_z_designdprt d where d.designdprtid=p.designdprtid and p.active = 1 and d.dprtid=" + deptId;
        List<String> userIds = jdbcTemplate.queryForList(sql, String.class);
        return this.constructeIdentityUsers(userIds);
    }

    /**
     * 根据设计人员获取设计科室->获得科室修改单计划员
     *
     * @param uId
     * @return
     */
    public Set<SysIdentity> getAmendPlannerByUId(Long uId) {
        JdbcTemplate jdbcTemplate = sysDataSourceService.getJdbcTemplateByKey(DBConstant.PLAN_DB);
        jdbcTemplate.execute("set collation_connection='utf8mb4_unicode_ci'");
        StringBuffer sqlBuff = new StringBuffer("select da.uid from proj_plantask_z_designdprt_amendPlanners da, proj_plantask_z_designdprt d ")
                .append(" where d.designdprtid = da.designdprtid and d.active=1 and da.active=1 ")
                .append(" and d.dprtid = ( select r.group_id_ from org_relation r where r.type_ = 'groupUser' AND r.user_id_ = '").append(uId).append("' )");
        List<String> userIds = jdbcTemplate.queryForList(sqlBuff.toString(), String.class);
        if (userIds == null || userIds.size() == 0) {
            userIds = new ArrayList<>();
            userIds.add("417137619324108800");//默认系统管理员
        }
        return this.constructeIdentityUsers(userIds);
    }

    /**
     * 根据通知部门配置表，获取节点处理人
     *
     * @param nid
     * @return
     */
    public Set<SysIdentity> getAmendNotifyUserId(Long nid) {
        JdbcTemplate jdbcTemplate = sysDataSourceService.getJdbcTemplateByKey(DBConstant.PLAN_DB);

        String sql = "select a.notify_user from proj_amend_z_notify_user a where a.id = ?;";
        String uids = jdbcTemplate.queryForObject(sql, new Object[]{nid}, String.class);

        return this.constructeIdentityUsersFromSpliceUserid(uids);
    }

    // 一对多示例会签
    public Set<SysIdentity> getAmendMulitiSign(String notifyIds) {
        Set<SysIdentity> firstUsers = new LinkedHashSet<>();
        String[] notifyIdArr = notifyIds.split(",");
        if (notifyIdArr.length > 5) {
            for (int i = 5; i < notifyIdArr.length; i++) {
                Set<SysIdentity> identities = getAmendNotifyUserId(Long.parseLong(notifyIdArr[i]));
                if (identities.size() > 0) {
                    firstUsers.add(identities.iterator().next());
                }
            }
        }
        return firstUsers;
    }

    /**
     * 据设计科室获取计划班组长
     *
     * @param deptId
     * @return
     */
    public Set<SysIdentity> getManagerHandlersByDeptId(Long deptId) {
        JdbcTemplate jdbcTemplate = sysDataSourceService.getJdbcTemplateByKey(DBConstant.PLAN_DB);
        String sql = "select uid from proj_plantask_z_designdprt_managers where active = 1 and designdprtid=" + deptId;
        List<String> userIds = jdbcTemplate.queryForList(sql, String.class);
        return this.constructeIdentityUsers(userIds);
    }

    /**
     * 据部门科室获取计划班组长
     *
     * @param deptId
     * @return
     */
    public Set<SysIdentity> getManagerByDeptId(Long deptId) {
        JdbcTemplate jdbcTemplate = sysDataSourceService.getJdbcTemplateByKey(DBConstant.PLAN_DB);
        String sql = "select m.uid from proj_plantask_z_designdprt_managers m,proj_plantask_z_designdprt d where d.designdprtid=m.designdprtid and m.active = 1 and d.dprtid=" + deptId;
        List<String> userIds = jdbcTemplate.queryForList(sql, String.class);
        return this.constructeIdentityUsers(userIds);
    }

    /**
     * 据员工id获取计划班组长
     *
     * @param userid
     * @return
     */
    public Set<SysIdentity> getManagerByUserId(Long userid) {
        Long deptId = etechGroupService.dprtidByUid(userid);
        JdbcTemplate jdbcTemplate = sysDataSourceService.getJdbcTemplateByKey(DBConstant.PLAN_DB);
        String sql = "select m.uid from proj_plantask_z_designdprt_managers m,proj_plantask_z_designdprt d where d.designdprtid=m.designdprtid and m.active = 1 and d.dprtid=" + deptId;
        List<String> userIds = jdbcTemplate.queryForList(sql, String.class);
        return this.constructeIdentityUsers(userIds);
    }

    /**
     * 获取部门班组的处长
     *
     * @param deptId
     * @return
     */
    public Set<SysIdentity> getManagersByDeptId(Long deptId) {
        JdbcTemplate jdbcTemplate = sysDataSourceService.getJdbcTemplateByKey(DBConstant.PLAN_DB);
        String sql = "select uid from wss_dprt_manager where active=1 and dprtid=" + deptId.longValue() + " order by orderby";
        List<String> userIds = jdbcTemplate.queryForList(sql, String.class);
        if (userIds != null && userIds.size() > 0) {
            return this.constructeIdentityUsers(userIds);
        } else {
            return Collections.emptySet();
        }
    }

    /**
     * 获取策略采购处领导，外协/配套的流程，自动选择沈超来审批，材料/自控的，自动选择丁喜红来审批；
     * 5248 外协-沈超 1332
     * 5249 材料-丁喜红 1562
     * 5250 配套-陈龙 400
     * 5251自控-陈龙 400
     *
     * @param userid 申请人uid
     * @return Set<SysIdentity>
     * @author PengMaochang
     * @date 2022/1/28 14:45
     */
    // TODO >>G
    public Set<SysIdentity> getLeaderByUserId(Long userid) {
        Long deptId = etechGroupService.dprtidByUid(userid);
        if (Arrays.asList(5250L, 5250L).contains(deptId)) {
            return this.constructeIdentityUsers(Arrays.asList("400"));
        } else if (Arrays.asList(5249L).contains(deptId)) {
            return this.constructeIdentityUsers(Arrays.asList("1562"));
        } else if (Arrays.asList(5248L).contains(deptId)) {
            return this.constructeIdentityUsers(Arrays.asList("1332"));
        } else {
            return this.constructeIdentityUsers(Arrays.asList("1562", "1332", "400"));
        }
    }

    /**
     * 根据部门科室获取PR负责人
     *
     * @param deptId
     * @return
     */
    public Set<SysIdentity> getPrPlannersByDeptId(Long deptId) {
        JdbcTemplate jdbcTemplate = sysDataSourceService.getJdbcTemplateByKey(DBConstant.PLAN_DB);
        String sql = "select uid from proj_plantask_z_designdprt_prPlanners where active = 1 and  designdprtid= " + deptId;
        List<String> userIds = jdbcTemplate.queryForList(sql, String.class);
        return this.constructeIdentityUsers(userIds);
    }

    // 检查当前用户是否具有某角色
    public boolean hasRole(String role) {
        if (role == null) {
            return false;
        }
        // 管理员特权
        if (isAdmin(ContextUtil.getCurrentUserId())) {
            return true;
        }

        return EtechUserUtil.checkUserHasRole(role);
    }

    //检查当前是否管理员
    private boolean isAdmin(String uid) {
        return "9".equals(uid) || "417137619324108800".equals(uid) || EtechUserUtil.getUserAdmin().getUserId().equals(uid);
    }

    //检查角色Key获取分配的指定人员
    public Set<SysIdentity> constructeIdentityUserByRole(String role) {
        if (StringUtil.isEmpty(role)) {
            return Collections.emptySet();
        }
        Set<SysIdentity> identities = new LinkedHashSet<>();
        List<String> ids = etechUserService.getUserIdsByRoleCode(role);
        if (ids != null && !CollectionUtils.isEmpty(ids)) {
            for (String id : ids) {
                IUser user = this.userService.getUserById(id);
                if (user != null && !StringUtil.isEmpty(user.getFullname())) {
                    SysIdentity identity = new DefaultIdentity(id, user.getFullname(), "user");
                    identities.add(identity);
                }
            }
        } else {
            this.log.warn("表单取候选人失败，表单字段为空 ： constructeIdentityUser id:{}", ids);
            return Collections.emptySet();
        }
        return identities;
    }

    public  boolean checkFactorys(List<String> facts) {
        boolean returnValue=false;
        if(facts!=null && !CollectionUtils.isEmpty(facts)){
            String conta="null";String contb="无要求";String contc="";
             for(int i=0;i<13;i++){
                if (facts.get(i).trim().equals(conta)||facts.get(i).trim().equals(contc)||facts.get(i).trim().equals(contb))
                {
                    returnValue = true;
                    return returnValue;
                }
            }
           if( facts.get(13).trim().equals("1"))
           {
               for(int i=14;i<22;i++){
                   if (facts.get(i).trim().equals(conta)||facts.get(i).trim().equals(contc)||facts.get(i).trim().equals(contb))
                   {
                       returnValue = true;
                       return returnValue;
                   }
               }
           }
           else if( facts.get(13).trim().equals("2"))
           {
               if (facts.get(22).trim().equals(conta)||facts.get(22).trim().equals(contc)||facts.get(22).trim().equals(contb))
               {
                   returnValue = true;
                   return returnValue;
               }
           }
           else if( facts.get(13).trim().equals("3"))
           {
               if (facts.get(23).trim().equals(conta)||facts.get(23).trim().equals(contc)||facts.get(23).trim().equals(contb))
               {
                   returnValue = true;
                   return returnValue;
               }
           }
        }
        return returnValue;
    }
}
